/**
 * Description:该类主要用于装载组件
 * Copyright: 成都和为科技有限公司 2012
 *
 * 属性
 *    load - 是否加载组件
 *    initload - 是否异步加载组件
 *    src - 组件路径
 */

function Component() {}

Component.inherit(Container);

/**
 * 初始化
 */
Component.prototype.init = function () {
	Component.base.init.call(this);
	this._load = false;
}

Component.prototype.initLoad = function() {
    this._paramDefine = {}; //参数定义
    this._param = {}; //组件参数
    this._handlerDefine = {}; //输入接口定义
    this._cHandlerDefine = {}; //输出接口定义
    this._layoutdata = {}; //组件布局信息
    this._exCHandler = {}; //输出接口排除组件

	this.setComponent(this);
    if (this.getAttribute().src) {
        this._path = this.getAttribute().src;
    }
    if (this.getAttribute().load
        && this.getAttribute().load == "false") {
        return;
    }
    if (this.getAttribute().initload
        && this.getAttribute().initload == "true") {
        var that = this;
        this.beginLoad();
        this.load(true, function(){
            that.endLoad();
        });
    } else {
        var that = this;
        this.load(false, function(){
        });
    }
}

Component.prototype.load = function(async, oCallBack) {
    //TODO 增加权限判断
    /**
     * 此处形成两层拦截
     *  1.从缓存中检查 该path是否存在权限控制,存在进入第二层,不存在继续执行
     *  2.从session中检查是否有权限,有则继续执行
     */
    var that = this;
    if (!async) async = false;
    $.ajax({
        async: async,
        cache: true,
        type: "GET",
        url: this.getPath(),
        dataType: "html",
        success: function (value) {
            var sHTML = value.substring(value.indexOf("<body>") + 6, value.indexOf("</body>"));
            var sTitle = value.substring(value.indexOf("<title>") + 7, value.indexOf("</title>"));
            if (that.getType() == "Application") {
                that.setTitle(sTitle);
            }
            try {
                $(that.getHTML()).append(sHTML);
            } catch (e) {
                console.error(e);
            }
            that.buildComponent();

            //装载组件内容
            that.buildElements(that.getHTML());
            if (that.getHandleClass() && that.getHandleClass().complete) {
                that.getHandleClass().complete(that);
            }
            that._load = true;
            if (oCallBack) oCallBack();
        },
        error: function (value) {
            console.error(value.responseText);
        }
    });
}

///**
// * 加载组件
// * showLoading 显示加载等待 - 默认false;
// */
//Component.prototype.load = function() {
//    //装载组件内容
//    this.buildElements(this.getHTML());
//    if (this.getHandleClass() && this.getHandleClass().complete) {
//        this.getHandleClass().complete(this);
//    }
//    this._load = true;
//}

/**
 * 卸载组件
 */
Component.prototype.unload = function() {
	this.unloadStyle();
    this.getHandleClass()._regMsgHandlers(false);//卸载接口
}

/**
 * 建立组件
 */
Component.prototype.buildComponent = function() {
    //装载Style
    this.loadStyle();
    //装载HandleClass
    this.loadHandleClass();
    //装载Script
    this.loadScript();
    //装载组件参数
    this.loadParamDefine();
    //装载组件输入接口
    this.loadHandlerDefine();
    //装载组件输出接口
    this.loadCHandlerDefine();
}


/**
 * 加载CSS文件
 * @param {} oAR
 */
Component.prototype.loadStyle = function() {
    var othis = this;
    $("div[data-control=Style]", this.getHTML()).each(function(){
        var src = $(this).attr("src");
        var sPath = othis.getAbsolutePath(src);
        var addtop = $(this).attr("addtop");
        othis.loadCSSFile(sPath, addtop);
    });
}

/**
 * 移除CSS File
 */
Component.prototype.unloadStyle = function() {
	var othis = this;
    $("div[data-control=Style]", this.getHTML()).each(function(){
        var src = $(this).attr("src");
        var sPath = othis.getAbsolutePath(src);
        othis.unloadCSSFile(sPath);
    });
}	

/**
 * 获得绝对路劲
 * @param {} path script or style path
 * @param {} oCmp component
 */
Component.prototype.getAbsolutePath = function(sPath) {
    if (sPath.substring(0,1) == ".") {
        var cPath = this.getPath();
        var sDir = cPath.substring(0, this.getPath().lastIndexOf("/"));
        sPath = sPath.substring(1);
        sPath = sDir + sPath;
    }
    return sPath;
}

/**
 * 加载处理类
 * @param {} oAR
 */
Component.prototype.loadHandleClass = function() {
    if ($("div[data-control=HandleClass]", this.getHTML()).length == 0) {
        //如果该网页没有处理类，则绑定一个，主要作用是为了让它的子类能够绑定消息到应用程序上
//    	console.log(this.getPath() + "未找到处理类");
        this._handleClass = new Portlet();
        this._handleClass.setComp(this);
        this._handleClass.init(null, this.getHTML());
    } else {
        this._className = $("div[data-control=HandleClass]", this.getHTML()).attr("className");
    }
}

/**
 * 加载脚本
 * @param {} oAR
 */
Component.prototype.loadScript = function() {
    var othis = this;
    $("div[data-control=Script]", this.getHTML()).each(function(){
        var src = $(this).attr("src");
        if (typeof(src) != "undefined") {
            var sPath = othis.getAbsolutePath(src);
            othis.loadScriptFile(sPath);
        }
    });
}

Component.prototype.loadScriptFile = function(src){
    //加载并执行js文件
    var othis = this;
    $.ajax({
        async: false,
        cache: true,
        type: "GET",
        url: src,
        dataType: "script",
        success: function() {
            if (!othis.getHandleClass()) {
                try {
                    othis._handleClass = eval("new " + othis._className + "()");
                } catch (e){
                };
                if (othis._handleClass) {
                    othis._handleClass.setComp(othis);
                    if (othis._handleClass.init)
                        othis._handleClass.init(othis);
                }
            }
        },
        error:function(e) {
            debugger;
        }
    });
}


Component.prototype.loadParamDefine  = function() {
    if (this._className && eval(this._className + ".PARAM_DEFINE")) {
        this._paramDefine = eval(this._className + ".PARAM_DEFINE");
        for (var name in this._paramDefine) {
            this._param[name] = this._paramDefine[name].value;
        }
    }
}

Component.prototype.loadHandlerDefine = function() {
    if (this._className && eval(this._className + ".HANDLER_DEFINE")) {
        this._handlerDefine = eval(this._className + ".HANDLER_DEFINE");
    }
}

Component.prototype.loadCHandlerDefine = function() {
    if (this._className && eval(this._className + ".CHANDLER_DEFINE")) {
        this._cHandlerDefine = eval(this._className + ".CHANDLER_DEFINE");
    }
}

Component.prototype.getParamDefine = function() {
    return this._paramDefine;
}

Component.prototype.getHandlerDefine = function() {
    return this._handlerDefine;
}

Component.prototype.getCHandlerDefine = function() {
    return this._cHandlerDefine;
}

/**
 * 判断组件是否载入
 */
Component.prototype.hasLoad = function(){
	return this._load;
}

/**
 * 销毁组件
 */
Component.prototype.destroy = function(){
	$(this._html).remove();
}

Component.prototype.getHandleClass = function() {
    return this._handleClass;
}

Component.prototype.setPath = function(sPath) {
    this._path = sPath;
}

Component.prototype.getPath = function() {
    return this._path;
}

/**
 * 是否加载
 * @returns {boolean|*|Component._load}
 */
Component.prototype.isLoad = function() {
    return this._load;
}

/**
 * 当一个页面有多个相同的组件，要获得组件发送消息.
 */
Component.prototype.postMessage = function(msg) {
	return this.getHandleClass().postMessage(msg);
}

/**
 * 设置组件布局信息
 */
Component.prototype.setLayoutData = function(oData) {
    this._layoutdata = oData;
}

/**
 * 获得组件布局信息
 */
Component.prototype.getLayoutData = function() {
    return this._layoutdata;
}

/**
 * 设置组件参数
 * @param oParam
 */
Component.prototype.setParam = function(oParam) {
    this._param = oParam;
}

/**
 * 获得组件参数
 * @returns {*}
 */
Component.prototype.getParam = function() {
    return this._param;
}

/**
 * 设置输出接口排除组件，默认调用有接口的所有组件
 * @param oHandler
 */
Component.prototype.setExCHandler = function(oExHandler) {
    this._exCHandler = oExHandler;
}

/**
 * 获得输出接口排除组件
 * @param oHandler
 */
Component.prototype.getExCHandler = function() {
    return this._exCHandler;
}

/**
 * 是否输出接口排除该组件
 * @param msgid  接口id
 * @param id 组件id
 */
Component.prototype.hasExCHandler = function(msgid, id) {
    if (this._exCHandler && this._exCHandler[msgid]) {
        var oExComps = this._exCHandler[msgid];
        for (var i = 0 ; i < oExComps.length ; i++) {
            if (oExComps[i] == id) {
                return true;
            }
        }
    }
    return false;
}

Component.newInstance = function(oAttr) {
	var oComp = Control.newInstance("Component", oAttr);
    oComp.init();
    oComp.initLoad();
    return oComp;
}

/**
 * 判断该组件是否有指定的消息接口
 * @param hander
 * @returns true/false
 */
Component.prototype.hasHander = function(hander) {
    var res = false;
    if(this._handleClass._oMsgH&& this._handleClass._oMsgH[hander]){
        res = true;
    }
    return res;
}

/**
 * 开启WebSocket接收事件
 * @param event 事件名称, 多个用逗号分割. 如：alarm,phone
 */
Component.prototype.openWebSocket = function(eventName) {
    var session = Cookie.getCookie("heweisessionid");
    if (typeof(g_sSession) != "undefined") {
        session = g_sSession;
    }
    if (!session) return;
    var host = window.location.host;
    var that = this;
    var websocket = new WebSocket("ws://" + host + "/websocket.do");
    websocket.onopen = function(event) {
        var data = {session:session, event:eventName};
        websocket.send(JSON.stringify(data));
    }
    websocket.onmessage = function(event) {
        var data = event.data;
        data = JSON.parse(data);
        that.postMessage({
            id:data.handler,
            content:data.content
        });
    }
}
